#coding=utf-8
import sys
sys.path.append("/")

import mido
from physicsLab import *

midi = mido.MidiFile("D:\\midi\\tongJi.mid")

mymidi = mido.MidiFile()
mymidi_track = mido.MidiTrack()
mymidi.tracks.append(mymidi_track)


notes1 = []
notes2 = []

for i, track in enumerate(midi.tracks):

    for msg in track:
        if msg.is_meta:
            continue

        msg = vars(msg)

        if msg["channel"] == 0:
            notes1.append(msg)
        elif msg["channel"] == 1:
            notes2.append(msg)

newTime: int = 0
note1Time, note2Time = 0, 0
breakSign = 0

note1_iter = iter(notes1)
note2_iter = iter(notes2)
note1 = next(note1_iter)
note2 = next(note2_iter)

# 用来记录newTime是否需要归位为-1
sign1 = False
sign2 = False

# 大体无问题，但貌似有轻微的错位
while breakSign != 2:
    try:
        newTime += 1
        note1Time += 1
        note2Time += 1

        if note1["time"] == note1Time:
            mymidi_track.append(mido.Message(note1["type"], note=note1["note"], velocity=note1["velocity"], time=newTime))
            note1 = next(note1_iter)
            newTime = 0
            note1Time = -1
            sign1 = True
        else:
            sign1 = False
        
        if note2["time"] == note2Time:
            mymidi_track.append(mido.Message(note2["type"], note=note2["note"], velocity=note2["velocity"], time=newTime))
            note2 = next(note2_iter)
            newTime = 0
            note2Time = -1
            sign2 = True
        else:
            sign2 = False
        
        if sign1 == True or sign2 == True:
            newTime = -1
        
    except StopIteration:
        breakSign += 1

mymidi.save("myTongJi.mid")